﻿using System;
using System.Windows.Forms;
using ApplicationGenerator.Forms.Utilities;
using ApplicationGenerator.Forms.WebControls;

namespace ApplicationGenerator.Forms.Forms
{
    public partial class SelectModelFieldForm : Form
    {
        private BaseMappedControl _baseMappedControl;
        private string _path;

        public string Path
        {
            get { return _path; }
        }

        public SelectModelFieldForm(BaseMappedControl baseMappedControl)
        {
            InitializeComponent();

            _baseMappedControl = baseMappedControl;
            modelHierarchyTree1.MetaAdapter = baseMappedControl.Source;
            modelHierarchyTree1.InitializeTree();
        }

        /// <summary>
        /// Trzeba napisać inaczej tę kontrolkę, żeby można jej też było użyć w workflow
        /// </summary>
        public SelectModelFieldForm()
        {
            InitializeComponent();
        }

        private void buttonSelect_Click(object sender, EventArgs e)
        {
            if (!modelHierarchyTree1.IsSelectedNode())
            {
                MessageBox.Show("Nie wybrano pola z drzewa modelu.", "Błąd walidacji");
                return;
            }

            if (!AreExpectedTypes(modelHierarchyTree1.GetSelectedFieldType(), _baseMappedControl.GetType()))
            {
                MessageBox.Show("Wybrane pole jest nieodpowiedniego typu dla danej kontrolki.", "Błąd walidacji");
                return;
            }

            string selectedField = modelHierarchyTree1.GetSelectedField();
            if (selectedField == null)
            {
                MessageBox.Show("Nie wybrano pola z drzewa modelu.", "Błąd walidacji");
                return;
            }

            _path = selectedField;

            DialogResult = DialogResult.OK;
            this.Close();

        }

        private bool AreExpectedTypes(Type modelFieldType, Type mappedControlType)
        {
            ControlTypeComparer typeComparer = new ControlTypeComparer();
            return typeComparer.AreValidTypes(mappedControlType, modelFieldType);
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            this.Close();
        }


    }
}
